<template>
  <div id="page">
    <el-table
      style="margin-top: 10px;"
      v-loading="listLoading"
      :data="tableData"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column v-for="(item,index) in colData" :key="index"
                       :label="item.label"
                       :width="item.width"
                       :align="item.align"
                       :class="item.class"
      >
        <template slot-scope="scope">
          <div v-if="item.type === 'status'">
            <el-tag :type="scope.row.status | statusFilter">{{ GetStatus(scope.row.status) }}
            </el-tag>
          </div>

          <div v-if="item.type === 'buttons'">
            <el-button v-for="(btn,_index) in item.buttons"
                       :type="btn.type"
                       :size="btn.size" @click="btn.callable(_index,scope.row)">
              {{btn.content}}
            </el-button>
          </div>

          <div v-if="!item.type">
            {{ scope.row[item.field] }}
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="count"
      style="margin-top: 10px"
      background
      layout="prev, pager, next"
      @current-change="ChangePage"
      :page-size="page_size"
      :total="count">
    </el-pagination>
  </div>
</template>
<script>
  export default {
    name: 'tableList',
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          0: 'danger'
        }
        return statusMap[status]
      }
    },
    props: {
      colData: {
        type: Array,
        default: []
      },
      tableUrl: {
        type: Function,
        default: () => {
        }
      },
      tableFilter: []
    },
    data() {
      return {
        tableData: [],
        listLoading: true,
        count: 0,
        page: 1,
        page_size: 5
      }
    },
    created() {
      this.LoadData();
    },
    methods: {
      render(key, callable = null) {
        let self = this;
        self.$set(this, key, false);
        this.$nextTick(() => {
          self.$set(this, key, true);
          if (callable) callable();
        })
      },
      LoadData() {
        let self = this;
        this.listLoading = false
        this.tableUrl({
          page: this.page,
          page_size: this.page_size,
          filter: self.tableFilter
        }).then(res => {
          self.tableData = res.data.list;
          self.count = res.data.count;
        })
      },
      ChangePage(index) {
        this.page = index;
        this.LoadData();
      },
      GetStatus(status) {
        let statusMap = {
          1: '开启',
          0: '关闭'
        }
        return statusMap[status]
      }
    }
  }
</script>
